package com.managertrade.service.impl;

import com.managertrade.config.ThreadLocalHolder;
import com.managertrade.dao.mysql.repository.DistributedLockRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.stereotype.Service;

import java.util.UUID;

@Service
@Slf4j
public class LockService {


    @Autowired
    private  DistributedLockRepository distributedLockRepository;
    // 应用启动时生成唯一标识，避免每次加锁用不同UUID导致无法释放
    private final String serverId = UUID.randomUUID().toString();



    /**
     * 尝试获取分布式锁
     */
    public boolean tryLock(String lockName) {
        String lockedBy = serverId; // 使用固定的服务唯一标识
        try {
            int rows = distributedLockRepository.acquireLock(lockName, lockedBy);
            if (rows > 0) {
                ThreadLocalHolder.setLockedBy(lockedBy);
                return true;
            }
        } catch (DataIntegrityViolationException e) {
            // 主键冲突，说明锁已被别人持有
            return false;
        } catch (Exception e) {
            // 其他异常打印出来，方便排查
            log.info("锁异常：{}",e.getStackTrace());
            return false;
        }
        return false;
    }

    /**
     * 释放锁
     */
    public void releaseLock(String lockName) {
        String lockedBy = ThreadLocalHolder.getLockedBy();
        if (lockedBy != null) {
            try {
                distributedLockRepository.releaseLock(lockName, lockedBy);
            } finally {
                ThreadLocalHolder.clear();
            }
        }
    }
}
